<script setup>
import { introApi } from "@/services/index";
import { onLoad, onShow, onHide } from "@dcloudio/uni-app";
import { nextTick, ref, watch, onMounted, onUnmounted } from "vue";

import topNav from "../../components/topNav.vue";
import code from "@/static/cashier/code.png";
import sand from "@/static/cashier/sand.png";
import num from "@/static/cashier/num.png";

import { appPayResult } from "@/services/cashier";
const id = ref("");
const payStatus = ref("");
const oriOrgTrace = ref("");
const outTrace = ref("");
const TimeGo = ref(null);
const TimeIndex = ref(5);
const payNum = ref(0);
const message = ref("");
const payPrice = ref(0);
onLoad((e) => {
  id.value = e.orderid ? e.orderid : "";
  payNum.value = e.payNum ? e.payNum : "";
  payPrice.value = e.payPrice ? e.payPrice : "";
});

onShow(() => {
  TimeIndex.value = 5;
  getPayResult();
});
onUnmounted(() => {
  if (TimeGo.value) {
    clearInterval(TimeGo.value);
  }
});
onHide(() => {
  if (TimeGo.value) {
    clearInterval(TimeGo.value);
  }
});

const getPayResult = async () => {
  let res = await appPayResult({ id: id.value });
  payStatus.value = res.data.result;
  // payStatus.value = "false";
  if (res.data.result == "wait") {
    setTimeout(() => {
      getPayResult();
    }, 1500);
  }

  if (res.data.result == "false") {
    message.value = res.data.message;
  }
  if (res.data.result == "true") {
    oriOrgTrace.value = res.data.oriOrgTrace;
    outTrace.value = res.data.saleorderCode;
    payPrice.value = res.data.actuallyAmt;
    arrAudio.value = res.data.voices;

    if (uni.getStorageSync("closeBroadcast")) {
    } else {
      playVideoTwo();
    }

    // PayYy();
    // console.log(moneyFomat(payPrice.value));

    TimeGo.value = setInterval(() => {
      if (TimeIndex.value <= 0) {
        clearInterval(TimeGo.value);
        // console.log("支付成功");
        goPay();

        return;
      }
      TimeIndex.value = TimeIndex.value - 1;
    }, 1000);
  }
};
const goPay = () => {
  uni.reLaunch({
    url: "/pages/cashier/goods/index",
  });
};
const goRPay = () => {
  uni.navigateBack(2);
  // uni.redirectTo({
  //   url: "/pages/cashier/goodsPayList/index?payNum=" + payNum.value,
  // });
};

//语音播报

const PayYy = () => {
  // payPrice.value
  money.value = moneyFomat(payPrice.value);
  console.log(money.value);
  playVideo("wechat");
};

const money = ref("");
const arrAudio = ref([]);
const arrNex = ref(0);
const innerAudioContext = ref(null);

const playVideoTwo = () => {
  // 创建并返回内部 audio 上下文 innerAudioContext 对象。

  try {
    innerAudioContext.value = uni.createInnerAudioContext();
    // #ifdef H5
    innerAudioContext.value.obeyMuteSwitch = true;
    // #endif

    // 避免出现autoplay失效问题
    innerAudioContext.value.autoplay = false;
    // #ifdef H5
    innerAudioContext.value.playbackRate = 2.0;
    // #endif

    // 先播放支付宝或微信收款语音
    innerAudioContext.value.src = arrAudio.value[arrNex.value]; // 音频存放到oss或本地
    setTimeout(() => {
      innerAudioContext.value.play();
    }, 100);

    innerAudioContext.value.onEnded(() => {
      endPlayTwo();
    });
  } catch (e) {
    console.log(e);
  }
};

const endPlayTwo = () => {
  // 播放金额音频文件
  arrNex.value = arrNex.value + 1;
  if (arrNex.value < arrAudio.value.length) {
    // 继续播放下一条
    innerAudioContext.value.src = arrAudio.value[arrNex.value];
    innerAudioContext.value.play();
    return;
  }
};

const moneyFomat = (n) => {
  if (!/^(0|[1-9]\d*)(\.\d+)?$/.test(n)) return "数据非法";
  var unit = "千百拾亿千百拾万千百拾元角分",
    str = "";
  n += "00";
  var p = n.indexOf(".");
  console.log(p);
  if (p >= 0) n = n.substring(0, p) + n.substr(p + 1, 2);
  unit = unit.substr(unit.length - n.length);

  // for (var i = 0; i < n.length; i++)
  //   str += "零壹贰叁肆伍陆柒捌玖".charAt(n.charAt(i)) + unit.charAt(i);
  for (var i = 0; i < n.length; i++) {
    // str += "零壹贰叁肆伍陆柒捌玖".charAt(n.charAt(i)) + unit.charAt(i);
    if (p > 0) {
      str +=
        "零壹贰叁肆伍陆柒捌玖".charAt(n.charAt(i)) +
        (i == p - 1 ? "点" : i < p - 1 ? unit.charAt(i) : "");
    } else {
      str += "零壹贰叁肆伍陆柒捌玖".charAt(n.charAt(i)) + unit.charAt(i);
    }
  }

  console.log(str);
  // return str
  //   .replace(/零(千|百|拾|角)/g, "")
  //   .replace(/(零)+/g, "")
  //   .replace(/零(万|亿|元)/g, "$1")
  //   .replace(/(亿)万|壹(拾)/g, "$1$2")
  //   .replace(/^元零?|零分/g, "")
  //   .replace(/元$/g, "元");
  return (
    str
      .replace(/零(千|百|拾|角)/g, "零")
      .replace(/(零)+/g, p < 0 ? "零" : "")
      .replace(/零(万|亿|元|点)/g, "$1")
      .replace(/(亿)万|壹(拾)/g, "$1$2")
      .replace(/^元零?|零分/g, "")
      .replace(/元$/g, "元") + (p > 0 ? "元" : "")
  );
};

const playVideo = (type) => {
  arrAudio.value = [];
  innerAudioContext.value = null;
  // 获取支付宝或微信语音
  arrAudio.value.push(type + "_recive");
  // 金额文字转为对应的音频名字
  for (let i = 0; i < money.value.length; i++) {
    switch (money.value[i]) {
      case "零":
        arrAudio.value.push("0");
        break;
      case "壹":
        arrAudio.value.push("1");
        break;
      case "贰":
        arrAudio.value.push("2");
        break;
      case "叁":
        arrAudio.value.push("3");
        break;
      case "肆":
        arrAudio.value.push("4");
        break;
      case "伍":
        arrAudio.value.push("5");
        break;
      case "陆":
        arrAudio.value.push("6");
        break;
      case "柒":
        arrAudio.value.push("7");
        break;
      case "捌":
        arrAudio.value.push("8");
        break;
      case "玖":
        arrAudio.value.push("9");
        break;
      case "拾":
        arrAudio.value.push("10");
        break;
      case "百":
        arrAudio.value.push("100");
        break;
      case "千":
        arrAudio.value.push("1000");
        break;
      case "万":
        arrAudio.value.push("10000");
        break;
      case "亿":
        arrAudio.value.push("10000000");
        break;
      case "分":
        arrAudio.value.push("fen");
        break;
      case "角":
        arrAudio.value.push("jiao");
        break;
      case "元":
        arrAudio.value.push("yuan");
        break;
      case "整":
        arrAudio.value.push("zheng");
        break;
      case "点":
        arrAudio.value.push("dian");
        break;
    }
  }
  // 创建并返回内部 audio 上下文 innerAudioContext 对象。
  innerAudioContext.value = uni.createInnerAudioContext();
  innerAudioContext.value.obeyMuteSwitch = true;
  // 避免出现autoplay失效问题
  innerAudioContext.value.autoplay = false;
  innerAudioContext.value.playbackRate = 2.0;
  innerAudioContext.value.obeyMuteSwitch = false;
  // 先播放支付宝或微信收款语音
  innerAudioContext.value.src =
    "../../../static/au/" + arrAudio.value[arrNex.value] + ".mp3"; // 音频存放到oss或本地
  setTimeout(() => {
    innerAudioContext.value.play();
  }, 100);
  // 连续播放
  // innerAudioContext.value.onEnded(() => {
  //   uni.showToast({
  //     title: "播放完成" + arrNex.value,
  //     icon: "success",
  //   });
  //   endPlay();
  // });
  innerAudioContext.value.onEnded(() => {
    endPlay();
  });
};

const endPlay = () => {
  // 播放金额音频文件
  arrNex.value = arrNex.value + 1;
  if (arrNex.value < arrAudio.value.length) {
    // 继续播放下一条
    innerAudioContext.value.src =
      "../../../static/au/" + arrAudio.value[arrNex.value] + ".mp3";
    innerAudioContext.value.play();
    return;
  }
};
//无网状态
const connected = () => {
  getPayResult();
};
</script>

<template>
  <view class="bg">
    <topNav
      :title="'支付状态'"
      @save="saveFun"
      :border="true"
      rType="save"
    ></topNav>

    <view class="payState" v-if="payStatus == 'false'">
      <view class="payState-top">
        <image src="@/static/cashier/icon_h.png" mode="scaleToFill" />
      </view>
      <view class="payState-title">支付失败</view>
      <view class="payState-des">{{ message }}</view>
      <view class="pay-to">
        <up-button
          @click="goRPay"
          class="pay-to-bt"
          type="primary"
          text="重新收款"
        ></up-button>
      </view>
    </view>
    <view v-if="payStatus == 'true'">
      <view class="payState">
        <view class="payState-top">
          <image src="@/static/cashier/icon_l.png" mode="scaleToFill" />
        </view>
        <view class="payState-title">收款成功</view>
        <view class="payState-des payState-des-num">¥{{ payPrice }}</view>
        <!-- <video src="../../../static/au/0.mp3" controls></video> -->

        <!-- <view class="pay-to">
          <up-button
            class="pay-to-bt"
            type="primary"
            text="更换收款方式"
          ></up-button>
        </view> -->
      </view>
      <view class="pay-info">
        <view class="pay-info-item">
          <text>订单编号</text>
          <text>{{ oriOrgTrace }}</text>
        </view>
        <view class="pay-info-item">
          <text>支付单号</text>
          <text>{{ outTrace }}</text>
        </view>
        <!-- <view class="pay-info-item">
          <text>商家</text>
          <text>42378742389</text>
        </view>
        <view class="pay-info-item">
          <text>买家</text>
          <text>42378742389</text>
        </view> -->
        <view class="select-pay">
          <up-button
            @click="goPay"
            class="select-pay-bt"
            type="primary"
            text="继续收银"
          ></up-button>
        </view>
        <!-- <view class="select-pay">
          <up-button
            @click="PayYy"
            class="select-pay-bt"
            type="primary"
            text="播放语音"
          ></up-button>
        </view> -->
        <view class="payState-time">{{ TimeIndex }}s后自动跳转...</view>
      </view>
    </view>

    <view class="payState" v-if="payStatus == 'unknown'">
      <view class="payState-top">
        <image src="@/static/cashier/icon_c.png" mode="scaleToFill" />
      </view>
      <view class="payState-title">无法操作</view>
      <view class="payState-des">无法联网，请检查您的网络</view>
      <view class="pay-to">
        <up-button
          class="pay-to-bt"
          type="primary"
          text="更换收款方式"
        ></up-button>
      </view>
    </view>

    <view class="payState" v-if="payStatus == 'wait'">
      <view class="payState-top">
        <image src="@/static/cashier/icon_lv.png" mode="scaleToFill" />
      </view>
      <view class="payState-title">等待处理</view>
      <view class="payState-des">收款中，请等待...</view>
      <!-- <view class="pay-to">
        <up-button
          class="pay-to-bt"
          type="primary"
          text="更换收款方式"
        ></up-button>
      </view> -->
    </view>
  </view>

  <noWork @connected="connected"> </noWork>
</template>

<style lang="scss" scoped>
@import "index.scss";
</style>
